package cc.rengu.oltp.service.common.dao.impl;

import cc.rengu.jradp.mods.xml.XmlTree;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.BinInfoMapper;
import cc.rengu.oltp.service.common.entity.BinInfo;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 卡BIN信息表操作接口实现类
 * Created by 王成 on 2018/4/20.
 */

public class BinInfoMapperImpl implements BinInfoMapper {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppParamConstant.OLTP_POOL_NAME);

    public BinInfoMapperImpl() throws Exception {
        if (XmlTree.hasThreadTree()) {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
            if (null != corporation && !corporation.isEmpty()) {
                String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppParamConstant.OLTP_POOL_NAME);
            }
        }
    }

    @Override
    public void loadAllCardBinInfo(Set<String> dbPoolCashNode, List<BinInfo> binInfoList) throws Exception {
        for (String dbCaseNodeName : dbPoolCashNode) {
            String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbCaseNodeName, AppParamConstant.OLTP_POOL_NAME);
            DbsUtil dbsUtil = new DbsUtil(dbPoolName);
            String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "loadAllCardBinInfo");
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageSize(5000);
            pageInfo.setPageIndex(0);
            //先查询一次，获取总笔数，不为无数据的错误都抛出异常
            PageResult result = dbsUtil.dbsFetchPageListData(sqlStr, new BinInfo(), BinInfo.class, pageInfo);
            if (null != result && null != result.getPageInfo()) {
                List<Object> objectList = result.getResult();
                if (null == objectList || objectList.isEmpty()) {
                    rglog.warn("卡BIN未配置!");
                    return;
                } else {
                    binInfoList.addAll(objectList.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList()));
                }
                pageInfo = result.getPageInfo();
                for (int i = 1; i < pageInfo.getTotalPage(); i++) {
                    pageInfo.setPageIndex(i);
                    PageResult resultTmp = dbsUtil.dbsFetchPageListData(sqlStr, new BinInfo(), BinInfo.class, pageInfo);
                    List<Object> objectListTmp = resultTmp.getResult();
                    pageInfo = resultTmp.getPageInfo();
                    if (null == objectListTmp || objectListTmp.isEmpty()) {
                        rglog.warn("获取数据库连接池【{}】全量卡BIN配置信息失败!", dbPoolName);
                        throw new Exception("获取全量卡BIN配置信息失败");
                    } else {
                        binInfoList.addAll(objectListTmp.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList()));
                    }
                }
            } else {
                rglog.warn("获取数据库连接池【{}】全量卡BIN配置信息失败!", dbPoolName);
                throw new Exception("获取全量卡BIN配置信息失败");
            }
        }
    }

    @Override
    public void loadAllCardBinInfo(List<BinInfo> binInfoList) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "loadAllCardBinInfo");
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, null, BinInfo.class);
        if (objectList.isEmpty()) {
            rglog.warn("获取数据库连接池【{}】全量卡BIN配置信息失败!", dbPoolName);
        } else {
            binInfoList.addAll(objectList.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList()));
        }
    }

    @Override
    public List<BinInfo> selectAllCardBinInfo() throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectAllCardBinInfo");
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, null, BinInfo.class);
        if (objectList.isEmpty()) {
            rglog.warn("获取全部卡BIN信息失败.");
            return null;
        }
        return objectList.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList());
    }

    @Override
    public List<BinInfo> selectAllCardBinInfoByIssuerCode(String issuerCode) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectAllCardBinInfoByIssuerCode");
        BinInfo binInfo = new BinInfo();
        binInfo.setIssuerCode(issuerCode);
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, binInfo, BinInfo.class);
        if (objectList.isEmpty()) {
            rglog.warn("根据发卡机构标识获取卡BIN信息失败,issuerCode:<{}>", issuerCode);
            return null;
        }
        return objectList.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList());
    }

    @Override
    public List<BinInfo> selectAllCardBinInfoByBinNo(String binNo) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectAllCardBinInfoByBinNo");
        BinInfo binInfo = new BinInfo();
        binInfo.setBinNo(binNo + "%");
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, binInfo, BinInfo.class);
        if (objectList.isEmpty()) {
            rglog.warn("根据卡BIN模糊查询获取卡BIN信息失败,issuerCode:<{}>", binNo);
            return null;
        }
        return objectList.stream().map(item -> (BinInfo) (item)).collect(Collectors.toList());
    }

    @Override
    public BinInfo selectCardBinInfoByPrimaryKey(String issuerCode, String binNo) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectCardBinInfoByPrimaryKey");
        BinInfo binInfo = new BinInfo();
        binInfo.setIssuerCode(issuerCode);
        binInfo.setBinNo(binNo);
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, binInfo, binInfo);
        if (0 != iReturnCode) {
            rglog.warn("根据主键获取卡BIN信息失败,issuerCode:<{}>,binNo:<{}>,iReturnCode:<{}>", issuerCode, binNo, iReturnCode);
            return null;
        }
        return binInfo;
    }

    @Override
    public int updateCardBinInfoByPrimaryKey(BinInfo binInfo) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateCardBinInfoByPrimaryKey");
        binInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, binInfo, null);
        if (0 != iReturnCode) {
            rglog.error("根据主键更新卡BIN信息失败,issuerCode:<{}>,binNo:<{}>,iReturnCode:<{}>", binInfo.getIssuerCode(), binInfo.getBinNo(), iReturnCode);
        }
        return iReturnCode;
    }

    @Override
    public int insertCardBinInfo(BinInfo binInfo) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "insertCardBinInfo");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, binInfo, null);
        if (0 != iReturnCode) {
            rglog.error("登记卡BIN信息失败,issuerCode:<{}>,binNo:<{}>,iReturnCode:<{}>", binInfo.getIssuerCode(), binInfo.getBinNo(), iReturnCode);
        }
        return iReturnCode;
    }
}
